package com.neusoft.neuiotms.dcam.fixed.service.spareconsume.impl;

import java.util.*;
import java.util.stream.Collectors;

import javax.persistence.EntityNotFoundException;

import com.neusoft.neuiotms.micro.auth.AuthMicroService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.bizcore.activiti.dto.ProcessInstanceDTO;
import com.neusoft.bizcore.activiti.service.ProcessInstanceService;
import com.neusoft.bizcore.activiti.service.WorkOrderService;
import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.neuiotms.dcam.common.model.DcamInstitutions;
import com.neusoft.neuiotms.dcam.common.model.DcamOperationGroup;
import com.neusoft.neuiotms.dcam.common.repository.DcamInstitutionsRepository;
import com.neusoft.neuiotms.dcam.common.repository.DcamOperationGroupRepository;
import com.neusoft.neuiotms.dcam.constant.DCAMConsts;
import com.neusoft.neuiotms.dcam.fixed.converter.spareconsume.SpareConsumeApplyConverter;
import com.neusoft.neuiotms.dcam.fixed.dto.spareconsume.SpareConsumeApplyDTO;
import com.neusoft.neuiotms.dcam.fixed.model.spareconsume.SpareConsumeApply;
import com.neusoft.neuiotms.dcam.fixed.repository.spareConsume.SpareConsumeApplyRepository;
import com.neusoft.neuiotms.dcam.fixed.service.spareconsume.SpareConsumeService;

@Service
public class SpareConsumeServiceImpl implements SpareConsumeService {

    @Autowired
    private WorkOrderService workOrderService;

    @Autowired
    private DcamInstitutionsRepository dcamInstitutionsRepository;

    @Autowired
    private DcamOperationGroupRepository dcamOperationGroupRepository;

    @Autowired
    private ProcessInstanceService processInstanceService;

    @Autowired
    private SpareConsumeApplyRepository spareConsumeApplyRepository;

    @Autowired
    private SpareConsumeApplyConverter spareConsumeApplyConverter;

    @Autowired
    private AuthMicroService authMicroService;

    @Transactional
    @Override
    public SpareConsumeApplyDTO create(final SpareConsumeApplyDTO dto, final UserBean user) {
        final String taskId = dto.getTaskId();
        // 设置标题
        final String title = StringUtils.isNotEmpty(dto.getTitle()) ? dto.getTitle()
                : user.getName() + "__" + dto.getMalfunctionName() + "备件领用工单";
        dto.setTitle(title);
        if(dto.getWorkNum() != null && "NULL".equals(dto.getWorkNum())){
            dto.setWorkNum("");
        }
        //判断是否为暂存状态
        if (DCAMConsts.STR_TEMPORARY.equals(dto.getStatus())) {
            // 暂存工单
            final String workNum =
                    this.workOrderService.temporaryStorage(title, DCAMConsts.SPARECONSUME_PROCESS_KEY,
                            dto.getWorkNum(), user);
            dto.setWorkNum(workNum);
        } else {

            final ProcessInstanceDTO instance =
                    this.workOrderService.submit(title, DCAMConsts.SPARECONSUME_PROCESS_KEY, dto.getWorkNum(), user);

            // 设置当前任务ID
            dto.setTaskId(instance.getTaskId());
            // 设置工单号
            dto.setWorkNum(instance.getWorkorderNum());

            if(isFirstlineEngineer(user)){
                // 获取提交人员编码编码
                final String frontlineEngineerCode = user.getUsername();

                // 查找一线运维人员对应的组长
                final DcamInstitutions institutions =
                        this.dcamInstitutionsRepository.findByResidents_UsernameIn(Arrays.asList(frontlineEngineerCode));
                if (null != institutions) {
                    final List<DcamInstitutions> institutionList = new ArrayList<>();
                    institutionList.add(institutions);
                    final DcamOperationGroup operationGroup =
                            this.dcamOperationGroupRepository.findByDcamInstitutionsIn(institutionList);
                    if (null != operationGroup) {
                        // 流程中设置组长的编码
                        this.processInstanceService.setGlobalVariable(instance.getTaskId(),
                                DCAMConsts.SPARECONSUME_PROCESS_EXECUTOR_OPERATION_TEAMLEADER,
                                operationGroup.getGroupLeaderCode());
                    }
                }
            }else{
                final Map<String, Object> queryMap = new HashMap<>();
                queryMap.put("s_roleCode",DCAMConsts.ROLE_EXPORT_LEADER );
                final List<Map<String, Object>> leaderList = this.authMicroService.userIndex(queryMap).getData();
                final List<String> leaders = new ArrayList<>();
                if(leaderList != null && leaderList.size() > 0 ){
                    leaderList.forEach(r->{
                        leaders.add(r.get("username") + "");
                    });
                }
                String leaderCode = "";
                if(leaders.size() > 0){
                    leaderCode = leaders.get(0);
                }
                this.processInstanceService.setGlobalVariable(dto.getTaskId(), DCAMConsts.SPARECONSUME_PROCESS_EXECUTOR_OPERATION_TEAMLEADER,
                        leaderCode);
            }

            // 完成节点
            this.processInstanceService.complete(dto.getWorkNum(), instance.getTaskId(), user);
        }

        // 查询当前workNum和TaskId下是否存在记录
        final SpareConsumeApply oldModel = this.spareConsumeApplyRepository.findByWorkNumAndTaskId(
                dto.getWorkNum(), taskId);
        // 如果不存在新增
        if (oldModel == null) {
            dto.setId(null);
        }

        final SpareConsumeApply model = this.spareConsumeApplyConverter.toModel(dto);
        this.spareConsumeApplyRepository.save(model);

        return this.spareConsumeApplyConverter.toDTO(model);
    }
	
	private boolean isFirstlineEngineer(UserBean userBean){
        boolean result = true;
        if(userBean != null){
            List<String> roles = userBean.getRoles().parallelStream().map(roleBean -> roleBean.getRole()).collect(Collectors.toList());
            result = !roles.contains(DCAMConsts.ROLE_EXPERT);
        }
        return result;
    }

    @Override
    public SpareConsumeApplyDTO detail(final String workNum, final String taskId, final UserBean user) {
        SpareConsumeApply model = null;

        try {
            if (StringUtils.isNotBlank(workNum) && !"NULL".equals(taskId)) {
                model = this.spareConsumeApplyRepository.findByWorkNumAndTaskId(workNum, taskId);
                if (model == null) {
                    // 获取前一节点的TaskID
                    final String fromProcessTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (fromProcessTaskId == null) {
                        return new SpareConsumeApplyDTO();
                    } else {
                        model = this.spareConsumeApplyRepository.findByWorkNumAndTaskId(workNum, fromProcessTaskId);
                    }
                }
            } else if ("NULL".equals(taskId)) {
                model = this.spareConsumeApplyRepository.findTopByWorkNumOrderByIdDesc(workNum);
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workNum },
                    new Object[] {taskId });
        }
        return this.spareConsumeApplyConverter.toDTO(model);
    }

    @Override
    public void deleteByWorkNum(final String workNum) {

    }

    @Override
    public String searchConfirmUser(String workOrderNum) {
        SpareConsumeApply apply = this.spareConsumeApplyRepository.findTopByWorkNumOrderByIdDesc(workOrderNum);
        return  apply.getConfirmUser();
    }
}
